//下降路径最小和
class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) 
    {
        int n=matrix.size();
        vector<vector<int>>dp(n,vector<int>(n,0));
        for(int i=0;i<n;i++)
        {
            dp[0][i]=matrix[0][i];
        }
        for(int i=1;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(j==0)
                {
                    dp[i][j]=min(dp[i-1][j],dp[i-1][j+1])+matrix[i][j];
                }
                else if(j==n-1)
                {
                    dp[i][j]=min(dp[i-1][j],dp[i-1][j-1])+matrix[i][j];
                }
                else 
                {
                    dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i-1][j+1]))+matrix[i][j];
                }
            }
        }
        int res=INT_MAX;
        for(int i=0;i<n;i++)
        {
            res=dp[n-1][i]<res?dp[n-1][i]:res;
        }
        return res;
    }
};

//地下城游戏
class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) 
    {
        //dp[i][j] 从[i,j]到达[m-1,n-1]的最低血量
        int m=dungeon.size();
        int n=dungeon[0].size();
        vector<vector<int>>dp(m+1,vector<int>(n+1,INT_MAX));
        dp[m-1][n]=dp[m][n-1]=1;
        for(int i=m-1;i>=0;i--)
        {
            for(int j=n-1;j>=0;j--)
            {
                dp[i][j]=min(dp[i+1][j],dp[i][j+1])-dungeon[i][j];
                dp[i][j]=max(1,dp[i][j]);
            }
        }
        return dp[0][0];
    }
};
